package com.rpc.protocal.serilization;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rpc.common.RpcRequest;
import com.rpc.common.RpcResponse;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;

/**
 * JsonSerialization
 *
 * @author 春江花朝秋月夜
 * @since 2024/1/17 12:19
 */
public class JsonSerialization implements RpcSerialization{
    private static final ObjectMapper JsonMapper;
    static
    {
        JsonMapper=getJsonMapper(JsonInclude.Include.ALWAYS);
    }
    //自定义Mapper
    private static ObjectMapper getJsonMapper(JsonInclude.Include include)
    {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(include);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
        objectMapper.configure(DeserializationFeature.FAIL_ON_NUMBERS_FOR_ENUMS,true);
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
        return objectMapper;
    }
    @Override
    public <T> byte[] serialize(T object) throws JsonProcessingException {
        return object instanceof String ? ((String) object).getBytes():JsonMapper.writeValueAsString(object).getBytes(StandardCharsets.UTF_8);
    }
    @Override
    public <T> T deserialize(byte[] data, Class<T> tClass) throws IOException {
        //先读取
        T value = JsonMapper.readValue(data, tClass);
        if (tClass.equals(RpcRequest.class))
        {
            RpcRequest rpcRequest= (RpcRequest) value;
            rpcRequest.setData(rpcRequest.getData());
            return (T) rpcRequest;
        }
        else
        {
            RpcResponse rpcResponse= (RpcResponse) value;
            rpcResponse.setData(rpcResponse.getData());
            return (T) rpcResponse;
        }
    }
}
